
package Interfaces;

import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import lemar.ConexionHibernate;
import lemar.entidad.Proveedor;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class ConsultarProveedor extends javax.swing.JPanel {

    //Atributos para el uso de Hibernate
    private static SessionFactory sessionFactory = null;
    
    public ConsultarProveedor() {
        initComponents();
        
        //Se carga el comboBox Dinamicamente de la BD
        cargarComboBox();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cmbNombreProveedor = new javax.swing.JComboBox();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        txtDireccionProveedor = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtTelefonoProveedor = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtProductosProveedor = new javax.swing.JTextField();
        btnConsultarProv = new javax.swing.JButton();

        setBackground(new java.awt.Color(255, 255, 255));
        setMaximumSize(new java.awt.Dimension(747, 435));
        setMinimumSize(new java.awt.Dimension(747, 435));
        setPreferredSize(new java.awt.Dimension(747, 435));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Consultar Datos De Proveedor");

        jLabel2.setText("Nombre Del Proveedor");

        cmbNombreProveedor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jSeparator1.setMaximumSize(new java.awt.Dimension(40, 10));
        jSeparator1.setMinimumSize(new java.awt.Dimension(40, 10));
        jSeparator1.setPreferredSize(new java.awt.Dimension(40, 10));

        jLabel3.setText("Dirección");

        txtDireccionProveedor.setEditable(false);

        jLabel4.setText("Teléfono");

        txtTelefonoProveedor.setEditable(false);
        txtTelefonoProveedor.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTelefonoProveedorKeyTyped(evt);
            }
        });

        jLabel5.setText("Productos que oferta");

        txtProductosProveedor.setEditable(false);

        btnConsultarProv.setText("Consultar");
        btnConsultarProv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarProvActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(252, 252, 252))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(152, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(cmbNombreProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel5))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtDireccionProveedor)
                                    .addComponent(txtTelefonoProveedor)
                                    .addComponent(txtProductosProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(201, 201, 201))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnConsultarProv)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 453, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(142, 142, 142))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addComponent(jLabel1)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cmbNombreProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtDireccionProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtTelefonoProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtProductosProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 90, Short.MAX_VALUE)
                .addComponent(btnConsultarProv)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void txtTelefonoProveedorKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTelefonoProveedorKeyTyped
        // SOLO NUMEROS
        char c;
        //capturar el caracter digitado
        c=evt.getKeyChar();
        if(c<'0'|| c>'9')
        {
        evt.consume();//ignora el caracter digitado 
        }
    }//GEN-LAST:event_txtTelefonoProveedorKeyTyped

    private void btnConsultarProvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarProvActionPerformed
        // TODO add your handling code here:
        String nombre = "";
        
        List<Proveedor> proveedor = null;
        
        //Se extrae el nombre del proveedor seleccionado
        nombre = cmbNombreProveedor.getSelectedItem().toString();
        
        if(nombre.equalsIgnoreCase("<--Seleccione un proveedor-->")){
            JOptionPane.showMessageDialog(null,"Seleccione un nombre de proveedor","Selección de datos",JOptionPane.ERROR_MESSAGE);
        }
        else{
            
            //Chunche de Hibernate (Inicio de sesion de hibernate)
            Session session = null;
            //Cadena de seleccion de HQL
            String hql = "FROM lemar.entidad.Proveedor AS p WHERE p.nombre = :nombre";
            try{
                try{
                    //Conexion a la BD
                    sessionFactory = ConexionHibernate.getSessionFactory();
                    //Apertura de la sesion
                    session = sessionFactory.openSession();
                    Transaction txt = session.beginTransaction();                                       
                    
                    //Extraccion de los datos del proveedor de la BD                    
                    Query query = session.createQuery(hql).setString("nombre", nombre);
                    
                    //Se extrae los registros del proveedor
                    proveedor = query.list();
                    
                    //Se ponen los datos del proveedir en los campos de texto
                    //para su respectiva consulta
                    
                    txtDireccionProveedor.setText(proveedor.get(0).getDireccion());
                    txtTelefonoProveedor.setText(proveedor.get(0).getTelefono());
                    txtProductosProveedor.setText(proveedor.get(0).getProductosOferta());
                    
                    txt.commit();
                    
                     
                    }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            } finally {
                //Finalizacion de la sesion de hibernate
                session.close();
                }
        }
    
    }//GEN-LAST:event_btnConsultarProvActionPerformed

    //Metodo para cargar el comboBox dinamicamente de la BD
    private void cargarComboBox(){
        
        //Obtencion de todos los proveedores de la base de datos
        //para llenar el comboBox de manera dinamica
        
        //Variable que contendra la lista de proveedores
        List<Proveedor> listaProveedor = null;
        
        //Inicializacion de session de hibernate
        Session session = null;
        try{
            try{
                //Chunces que ocupa Hibernate
                sessionFactory = ConexionHibernate.getSessionFactory();
                session = sessionFactory.openSession();
                Transaction tx = session.beginTransaction();
                
                //Obteniendo de la BD todos los proveedores                
                listaProveedor = session.createQuery("from Proveedor").list();
                
                //Creando un modelo de comboBox                
                DefaultComboBoxModel modeloCombo = new DefaultComboBoxModel();
                
                //Poniendole un mensaje de seleccion (Pirmer elemento)
                 modeloCombo.addElement("<--Seleccione un proveedor-->");
                
                //Llenando el modelo de comboBox con los nombres de los proveedores
                for(Proveedor p : listaProveedor) 
                { 
                    modeloCombo.addElement(p.getNombre());                     
                }
                
                //Agregando el modelo del comboBox al comboBox del panel
                cmbNombreProveedor.setModel(modeloCombo);
                
            }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            }finally {
                session.close();
        }
        
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConsultarProv;
    private javax.swing.JComboBox cmbNombreProveedor;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField txtDireccionProveedor;
    private javax.swing.JTextField txtProductosProveedor;
    private javax.swing.JTextField txtTelefonoProveedor;
    // End of variables declaration//GEN-END:variables
}
